//201902104030_何琛选
package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.User;
import cn.edu.sdjzu.xg.bysj.domain.authority.Actor;
import cn.edu.sdjzu.xg.bysj.domain.authority.Role;
import cn.edu.sdjzu.xg.bysj.service.ActorService;
import com.alibaba.fastjson.JSONObject;
import util.JdbcHelper;
import util.TokenHelper;

import java.sql.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;

public final class UserDao {
    private static UserDao userDao = new UserDao();
    private static Collection<User> users;

    private UserDao() {
    }

    public static UserDao getInstance() {
        return userDao;
    }

    public Collection<User> findAll(Connection conn) throws SQLException {
        Collection<User> users = new TreeSet<>();
        //预编译方式进行查询
        String s = "select * from user";
        PreparedStatement preparedStatement = conn.prepareStatement(s);
        ResultSet resultSet = preparedStatement.executeQuery();
        //将查询到的数据存到departments集合中
        while (resultSet.next()){
            int id = resultSet.getInt(1);
            String username = resultSet.getString(2);
            String password = resultSet.getString(3);
            Timestamp timestamp = resultSet.getTimestamp(4);
            Collection<Role> roles = null;
                    //UserAssRoleDao.getInstance().find(id, conn);
            User user = new User(id, username, password, timestamp.toLocalDateTime(),null);
            users.add(user);
        }
        JdbcHelper.close(resultSet,preparedStatement,conn);
        return users;
    }

    public User find(Integer id,Connection connection) throws SQLException{
        //Connection connection = JdbcHelper.getConn();
        String user_sql = "select * from User where id = ?";
        //在连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(user_sql);
        //为预编译参数赋值
        pstmt.setInt(1, id);
        //根据id查找user
        ResultSet resultSet = pstmt.executeQuery();
        resultSet.next();
        //根据id查找结果创建user对象
        User user = new User(
                );
        //关闭
        JdbcHelper.close(resultSet,pstmt, connection);
        return user;
    }

    public boolean update(User user,Connection connection) {
        users.remove(user);
        return users.add(user);
    }

    public boolean add(User user, Connection connection) throws SQLException {
        //创建语句对象，字段LastLoginTime 为“时间戳”类型
        PreparedStatement preparedStatement = connection.prepareStatement(
                "INSERT INTO user" +
                "(username,password,actor_id)"+
                "VALUE (?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,user.getUsername());
        preparedStatement.setString(2,user.getPassword());
        preparedStatement.setInt(3,user.getActor().getId());

        //执行语句
        int affectedRowNum = preparedStatement.executeUpdate();
        int idOfAddUser = 0;
        //获得生成的主键集合
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()){
            //读取第一个主键
            idOfAddUser = resultSet.getInt(1);
        }
        return idOfAddUser>0;
    }

    public boolean delete(Integer id,Connection connection) throws SQLException {
        //创建sql语句
        String deleteUser_sql = "delete from user where id=?";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(deleteUser_sql);
        //为预编译参数赋值
        pstmt.setInt(1,id);

        return pstmt.executeLargeUpdate()>0;
    }

    public boolean delete(User user,Connection connection) throws SQLException{
        String deleteUser_sql = "delete from degree where username = ?";
        //在连接上创建预编译语句对象
        PreparedStatement pstmt = connection.prepareStatement(deleteUser_sql);
        //为预编译参数赋值
        pstmt.setString(1,user.getUsername());
        //根据id删除学院 并判断是否删除成功
        return pstmt.executeUpdate()>0;
    }

    public Actor login(Connection connection, User user,
                       JSONObject message) throws SQLException {
        //创建Teacher类型的引用，暂不创建对象
        Actor currentActor = null;
        String sql_login = "SELECT * FROM user WHERE username =? and password=?";
        PreparedStatement pstmt_login =
                connection.prepareStatement(sql_login);
        pstmt_login.setString(1, user.getUsername());
        pstmt_login.setString(2, user.getPassword());
        ResultSet resultSet_login = pstmt_login.executeQuery();
        //如果表中存在id对应的记录，则获得表中的actor_id，并获得对应的Actor对象
        if (resultSet_login.next()) {
            int actor_id = resultSet_login.getInt("actor_id");
            currentActor = ActorService.getInstance().find(actor_id);
        }
        HashMap<Integer,String> map = new HashMap<Integer,String>();
        map.put(1,"HeChenXuan,QianYue");
        String token = TokenHelper.getToken(map);
        message.put("token",token);
        return currentActor;
    }
}